import React from 'react';
// import { withRouter, Link } from 'umi';
import { withRouter } from 'umi';
import { Form, Input, Row, Divider, Skeleton, Spin } from 'antd';
import { Collapse } from '@/molecules';
import { useRequest, defaultFormatResult, useCollapse } from '@/hooks';
import { PersonalCard } from '@/pages/Informal/containers';
import { BraftTemplate } from '@/pages/TurnoverSetting/containers';
import { getInformalEmployeeInfo } from '@/pages/Informal/services';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
// import { ResultTable, PerformanceTable, ArrangeTable } from './containers';
import { getSummary } from '@/pages/WorkFlow/Flow/utils';

import { ResultTable, ArrangeTable } from './containers';
import { getInformalApplyInfo, getInformalDetail } from './services';
import styles from './index.less';

const { Panel } = Collapse;

const PAGE = {
    FLOW: 1, // 流程配置页
    APPLY: 2, // 申请页
    DETAIL: 3 // 审批详情页
};

const Regular = ({ location, form, formValueMap = {}, dataSource }) => {
    const { query } = location;
    const { children: list } = dataSource;
    // console.log('🚀 ~ Regular ~ formValueMap', formValueMap);

    const { activeKey, onChange } = useCollapse(['1', '2', '3', '4'], []);

    const { data: employeeInfo, loading: infoLoading } = useRequest(
        () => getInformalEmployeeInfo(query?.employeeCode),
        {
            refreshDeps: [query?.employeeCode],
            ready: !!query?.employeeCode,
            ...defaultFormatResult
        }
    );
    // console.log('🚀 ~ Regular ~ employeeInfo', employeeInfo);

    const { data: detailInfo } = useRequest(() => getInformalDetail(query?.employeeCode), {
        refreshDeps: [query?.employeeCode],
        ready: !!query?.employeeCode,
        ...defaultFormatResult
    });
    // console.log('🚀 ~ detailInfo', detailInfo);

    const { data: applyInfo } = useRequest(() => getInformalApplyInfo(query?.employeeCode), {
        refreshDeps: [query?.employeeCode],
        ready: !!query?.employeeCode,
        ...defaultFormatResult
    });

    const pageType = React.useMemo(() => {
        const size = Object.keys(formValueMap).length;
        if (size > 0) {
            return PAGE.DETAIL;
        }
        if (query?.employeeCode) {
            return PAGE.APPLY;
        }
        return PAGE.FLOW;
    }, [query, JSON.stringify(formValueMap)]);

    const checkPass = v =>
        pageType !== PAGE.APPLY ||
        applyInfo?.fillInRule !== 2 ||
        (v &&
            v !== '<p></p>' &&
            v !== '<p size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"></p>');

    const { getFieldDecorator, getFieldValue, setFieldsValue } = form;

    getFieldDecorator('regularApply', {
        initialValue: '',
        rules: [
            {
                validator(rule, value, callback) {
                    if (checkPass(value)) {
                        callback();
                    }
                    callback('转正申请表不能为空');
                }
            }
        ]
    });

    const regularApplyValue = getFieldValue('regularApply');

    const isPassed = checkPass(regularApplyValue);

    const handleChange = React.useCallback(html => {
        setFieldsValue({
            regularApply: html
        });
    }, []);

    getFieldDecorator('detailInfo');
    getFieldDecorator('employeeInfo');

    React.useEffect(() => {
        if (detailInfo) {
            setFieldsValue({
                detailInfo
            });
        }
    }, [JSON.stringify(detailInfo)]);

    React.useEffect(() => {
        if (employeeInfo) {
            setFieldsValue({
                employeeInfo
            });
        }
    }, [JSON.stringify(employeeInfo)]);

    const summary = getSummary({
        转正员工: employeeInfo?.employeeName || formValueMap?.employeeInfo?.employeeName || '',
        转正日期: employeeInfo?.expectRegularDate || formValueMap?.employeeInfo?.expectRegularDate || '',
        岗位职级: `${employeeInfo?.dutyName || formValueMap?.employeeInfo?.dutyName || ''} ${employeeInfo?.rankValue ||
            formValueMap?.employeeInfo?.rankValue ||
            ''}`,
        部门: employeeInfo?.organizationName || formValueMap?.employeeInfo?.organizationName || ''
    });

    return (
        <Spin spinning={infoLoading}>
            <Row>
                {pageType === PAGE.FLOW && <Skeleton avatar paragraph={{ rows: 4 }} />}
                {pageType !== PAGE.FLOW && <PersonalCard data={employeeInfo || formValueMap?.employeeInfo} />}
                <Divider style={{ margin: '24px 0 0' }} />
                <Collapse bordered={false} style={{ marginBottom: 16 }} activeKey={activeKey} onChange={onChange}>
                    <Panel header="试用考评结果" key="1">
                        <ResultTable
                            dataSource={detailInfo?.assess || formValueMap?.detailInfo?.assess || []}
                            levels={
                                detailInfo?.abilityAssessVO?.levels ||
                                formValueMap?.detailInfo?.abilityAssessVO?.levels ||
                                []
                            }
                        />
                    </Panel>
                    {/* <Panel header="试用期绩效" key="2">
                        <Form className={styles.formWrap}>
                            <Form.Item label="绩效要求">
                                综合各季度绩效结果不低于【
                                {detailInfo?.performanceExplain?.requirementsLevel ||
                                    formValueMap?.detailInfo?.performanceExplain?.requirementsLevel ||
                                    '--'}
                                】级，否则为不合格
                            </Form.Item>
                            <Form.Item label="绩效结果">
                                <PerformanceTable
                                    dataSource={detailInfo?.performance || formValueMap?.detailInfo?.performance || []}
                                />
                            </Form.Item>
                        </Form>
                    </Panel> */}
                    <Panel header="过程记录" key="3">
                        <Form className={styles.formWrap}>
                            {/* <Form.Item label="试用反馈">
                                <Link
                                    to={{
                                        pathname:
                                            '/office/personnelManagement/onboardAndLeave/informal/feedback/record',
                                        query: {
                                            employeeCode:
                                                query?.employeeCode || formValueMap?.employeeInfo?.employeeCode || '',
                                            id: employeeInfo?.id || formValueMap?.employeeInfo?.id || ''
                                        },
                                        state: { tabRoute: true, tabRefresh: true }
                                    }}
                                >
                                    查看反馈详情
                                </Link>
                            </Form.Item> */}
                            <Form.Item label="面谈记录">
                                <ArrangeTable
                                    dataSource={
                                        detailInfo?.interviewArrangeVOList ||
                                        formValueMap?.detailInfo?.interviewArrangeVOList ||
                                        []
                                    }
                                />
                            </Form.Item>
                            {/* <Form.Item label="奖惩记录">
                                <ResultTable />
                            </Form.Item>
                            <Form.Item label="培训记录">
                                <ResultTable />
                            </Form.Item> */}
                        </Form>
                    </Panel>
                    <Panel header="转正申请" key="4">
                        <Form className={styles.formWrap}>
                            <Form.Item label="试用期总结">
                                {(pageType === PAGE.DETAIL && (
                                    <div
                                        style={{
                                            whiteSpace: 'pre-wrap',
                                            wordBreak: 'break-all',
                                            lineHeight: 1.5,
                                            marginTop: 10
                                        }}
                                    >
                                        {formValueMap?.summary}
                                    </div>
                                )) ||
                                    ''}
                                {pageType !== PAGE.DETAIL &&
                                    getFieldDecorator('summary', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                required: true,
                                                message: '试用期总结不能为空'
                                            }
                                        ]
                                    })(
                                        <Input.TextArea
                                            placeholder="请输入试用期总结"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={4000}
                                            disabled={pageType === PAGE.FLOW}
                                        />
                                    )}
                            </Form.Item>
                            {([1, 2].includes(applyInfo?.fillInRule) || formValueMap?.regularApply) && (
                                <Form.Item
                                    label="转正申请表"
                                    help={isPassed ? '' : '转正申请表不能为空'}
                                    validateStatus={isPassed ? '' : 'error'}
                                    required={applyInfo?.fillInRule === 2}
                                >
                                    <BraftTemplate
                                        prefix="regular"
                                        onChange={handleChange}
                                        hasField={false}
                                        initialValue={formValueMap?.regularApply || applyInfo?.content || ''}
                                        placeholder="请输入转正申请表"
                                        readOnly={pageType === PAGE.DETAIL}
                                        disabled={pageType === PAGE.FLOW}
                                    />
                                </Form.Item>
                            )}
                            {list?.map(item => {
                                const { label, formId, rules, extra } = item;
                                const { initialValue } = item;
                                return (
                                    <Form.Item label={label} key={formId} extra={extra}>
                                        {getFieldDecorator(formId, {
                                            initialValue,
                                            rules
                                        })(<AutoRenderComponent form={form} config={item} />)}
                                    </Form.Item>
                                );
                            })}
                        </Form>
                    </Panel>
                </Collapse>
                {/* 摘要 */}
                <Form.Item style={{ display: 'none' }}>
                    {form.getFieldDecorator('applicationAbstract', {
                        initialValue: summary
                    })(<Input />)}
                </Form.Item>
            </Row>
        </Spin>
    );
};

export default withRouter(Regular);
